<script>
const preventSystemBackModal = uni.requireNativePlugin('HG-PreventBack');
// tar小红点
// import { setTabBarBadge } from '@/utils/TabBarBadge.js';
import { clearStorage, removeAllCookie, setStorage, removeCookie, getStorage, removeStorage } from '@/utils/setStorage.js';
import { baseUrl } from '@/utils/http.js';
import { loadFontFace } from '@/utils/loadFontFaceBox.js';
export default {
	globalData: {
		pushClientId: '',
		pitch: 1,
		speed: 1,
		bians: false,
	},
	onLaunch: function() {
		// 隐藏系统虚拟按键（导航栏）
		plus.navigator.hideSystemNavigation();
		// 锁定横屏
		// plus.screen.lockOrientation("landscape-primary");
		// 锁定竖屏
		// plus.screen.lockOrientation('portrait-primary');
		// console.log('App Launch');
		// 只有第一次打开app才执行,做默认操作
		const obj = {
			type: 'login',
			value: 1
		};
		// 关闭app，重新打开后。重置为登录的type
		setStorage('tokenNum', obj);
		// 获取个推cid
		plus.push.getClientInfoAsync(
			res => {
				getApp().globalData.pushClientId = res.clientid;
				console.log(res.clientid);
				this.$scope.globalData.pushClientId = res.clientid;
			},
			err => {
				console.log(err);
			}
		);
		plus.push.setAutoNotification(true); //设置通知栏显示通知 //必须设置
		//监听接收透传消息事件
		// // #ifdef APP-PLUS
		plus.push.addEventListener(
			'click',
			msg => {
				// #ifdef APP-PLUS
				// 设置数字
				// plus.runtime.setBadgeNumber(1);
				// plus.push.clear(); // 清空所有推送消息
				this.pushHandle(msg); //处理方法
				// #endif
			},
			false
		);
		// //监听接收透传消息事件
		plus.push.addEventListener(
			'receive',
			function(msg) {
				// plus.push.clear(); // 清空所有推送消息
				switch (uni.getSystemInfoSync().platform) {
					case 'android':
						console.log(msg);
						if (msg.payload && msg.payload != null) {
							const content = msg.payload;
							//这里根据你消息字段来创建消息
							let options = { cover: false, sound: 'system', title: content.title };
							plus.push.createMessage(content.body, JSON.stringify(content), options); //创建本地消息
						}
						break;

					case 'ios':
						if (msg.payload && msg.payload != null && msg.type == 'receive') {
							const content = msg.payload;
							// // {"title": "xxx","content": "xxx","payload": "xxx"} 符合这种 才会自动创建消息  文档地址https://ask.dcloud.net.cn/article/35622
							let options = { cover: false, sound: 'system', title: content.title };
							plus.push.createMessage(content.body, JSON.stringify(content), options); //创建本地消息
						}
						break;
				}
			},
			false
		);
		// // #endif
		// 加载字体包
		this.$nextTick(function() {
			loadFontFace();
		});
		// 获取schema跳转传参
		// var args = plus.runtime.arguments;
		// if (args) {
		// 	uni.showToast({
		// 		title: args,
		// 		icon: 'none',
		// 		position: 'top'
		// 	});
		// 	// 处理args参数，如直达到某新页面等
		// }
		setTimeout(() => {
			this.judgeIosPermissionPush();
		}, 2000);
	},
	onShow: function() {
		// console.log(arr);
		// 清除数字
		// function clearBadge() {
		// 	plus.runtime.setBadgeNumber(0);
		// }
		// console.log(plus.runtime.versionCode);
		// if (!this.bians) {
		// 	this.update();
		// }
		// setTabBarBadge(1, '3');
		console.log('App Show');
		// var back_k = 0;
		// let main = plus.android.runtimeMainActivity();
		switch (uni.getSystemInfoSync().platform) {
			case 'android':
				this.update(0);
				preventSystemBackModal.setUp(
					{
						enable: true //是否拦截系统返回功能
					},
					ret => {
						uni.$emit('goBack_k', true);
						// if (back_k > 0) {
						// 	return main.moveTaskToBack(false);
						// 	// return plus.runtime.quit();
						// } else {
						// 	const pages = getCurrentPages();
						// 	if (pages.length === 1) {
						// 		back_k++;
						// 		setTimeout(() => {
						// 			back_k--;
						// 		}, 1000);
						// 		uni.showToast({
						// 			title: '再按一次退出应用',
						// 			icon: 'none',
						// 			duration: 1000
						// 			// position: 'top'
						// 		});
						// 	} else {
						// 		uni.navigateBack({
						// 			delta: 1
						// 		});
						// 	}
						// }
					}
				);
				console.log('android');

				break;

			case 'ios':
				console.log('ios');
				this.update(1);
				break;
		}
		// 获取当前页面
		// this.getOnePages();
	},
	onHide: function() {
		setStorage('loginShow', 1); // tabbar点击
		if (getStorage('tokenNum')) {
			if (getStorage('tokenNum').value === 2) {
				const lang = getStorage('language') || 'th';
				clearStorage();
				removeAllCookie();
				removeCookie(baseUrl);
				// 多语言重新赋值
				setTimeout(() => {
					setStorage('language', lang);
					const obj = {
						type: 'hide',
						value: 1
					};
					setStorage('tokenNum', obj);
				}, 300);
			}
		}
		console.log('App Hide');
		// 清除弹框1
		removeStorage('popUpOneShow');
		// 清除弹框2
		removeStorage('popUpTwoShow');
		// 清除弹框3
		removeStorage('popUpThreeShow');
	},
	onReady() {},
	created() {},
	methods: {
		async update(val) {
			var _this = this;
			const params = {
				appType: val
			};
			const { data: res } = await this.$http(true, 'api/app/getNewest', params, 'GET');
			if (res.errno === 0) {
				if (res.data) {
					const version = plus.runtime.version.split('.').join(''); // 获取当前app版本号
					const paramsOption = {
						isUpdate: res.data.isUpdate,
						message: res.data.message,
						cancelButton: res.data.cancelButton,
						wgtUrl: res.data.wgtUrl,
						appUrl: res.data.appUrl
					};
					const newversion = res.data.appVersion.split('.').join('');
					if (version < newversion && Number(res.data.dialog) == 2) {
						paramsOption.isUpdate = 2;
						setTimeout(() => {
							// #ifdef APP-PLUS
							uni.navigateTo({
								url: `/pages/popupPages/index?paramsOption=${encodeURIComponent(JSON.stringify(paramsOption))}`
							});
							// uni.navigateTo({
							// 	url: `/pages/popupPages/index?isUpdate=${res.data.isUpdate}&message=${res.data.message}&appUrl=${res.data.appUrl}&cancelButton=${res.data.cancelButton}&wgtUrl=${res.data.wgtUrl}`
							// });
							// #endif
						}, 1000);
					} else if (version == newversion && Number(res.data.dialog) == 2) {
						paramsOption.isUpdate = 1;
						plus.runtime.getProperty(plus.runtime.appid, function(wgtinfo) {
							let oldwgtver = wgtinfo.version.split('.').join('');
							let wgtVersion = '';
							if (res.data.wgtVersion) {
								wgtVersion = res.data.wgtVersion;
							}
							if (oldwgtver < wgtVersion) {
								setTimeout(() => {
									// #ifdef APP-PLUS
									uni.navigateTo({
										url: `/pages/popupPages/index?paramsOption=${encodeURIComponent(JSON.stringify(paramsOption))}`
									});
									// uni.navigateTo({
									// 	url: `/pages/popupPages/index?isUpdate=${res.data.isUpdate}&message=${res.data.message}&appUrl=${res.data.appUrl}&cancelButton=${res.data.cancelButton}&wgtUrl=${res.data.wgtUrl}`
									// });
									// #endif
								}, 1000);
							}
						});
					}
				}
			}
		},
		// 接收推送到消息时
		pushHandle(msg) {
			// if (typeof msg.payload == 'string') {
			// 	//如果是字符串，表示是ios创建的  要转换一下
			// 	msg.payload = JSON.parse(msg.payload);
			// }
			console.log(msg);
			if (!msg) return false;
			plus.runtime.setBadgeNumber(0); //清除app角标
			plus.push.clear(); // 清空所有推送消息
			if (msg.aps && msg.aps != null) {
				if (msg.aps.alert.billCode) {
					setTimeout(() => {
						this.$nextTick(function() {
							// #ifdef APP-PLUS
							uni.redirectTo({
								url: `/pages/maps/orderTracking?num=${msg.aps.alert.billCode}&url=/pages/maps/index`
							});
							// #endif
							// #ifdef H5
							this.$Router.push(`/pages/maps/orderTracking?num=${msg.aps.alert.billCode}&url=/pages/maps/index`);
							// #endif
						});
					}, 1000);
				} else if (msg.aps.alert.title == 'RMB Exchange Rate update') {
					setTimeout(() => {
						this.$nextTick(function() {
							// #ifdef APP-PLUS
							uni.redirectTo({
								url: `/pages/exchangeRate/index`
							});
							// #endif
							// #ifdef H5
							this.$Router.push(`/pages/exchangeRate/index`);
							// #endif
						});
					}, 1000);
				}
			} else {
				if (msg.payload) {
					switch (uni.getSystemInfoSync().platform) {
						case 'android':
							const content = msg.payload;
							if (content.title == 'RMB Exchange Rate update') {
								setTimeout(() => {
									this.$nextTick(function() {
										// #ifdef APP-PLUS
										uni.redirectTo({
											url: `/pages/exchangeRate/index`
										});
										// #endif
										// #ifdef H5
										this.$Router.push(`/pages/exchangeRate/index`);
										// #endif
									});
								}, 500);
								return;
							} else {
								if (content.billCode) {
									setTimeout(() => {
										this.$nextTick(function() {
											// #ifdef APP-PLUS
											uni.redirectTo({
												url: `/pages/maps/orderTracking?num=${content.billCode}&url=/pages/maps/index`
											});
											// #endif
											// #ifdef H5
											this.$Router.push(`/pages/maps/orderTracking?num=${content.billCode}&url=/pages/maps/index`);
											// #endif
										});
									}, 1000);
								} else {
									const ss = content.title.split('/');
									const arr = [];
									ss.forEach(item => {
										const arr2 = item.split(':');
										arr2.forEach(item2 => {
											const str2 = item2.replace(/\s+/g, '');
											arr.push(str2);
										});
									});
									if (arr.length > 0) {
										setTimeout(() => {
											this.$nextTick(function() {
												// #ifdef APP-PLUS
												uni.redirectTo({
													url: `/pages/maps/orderTracking?num=${arr[1]}&url=/pages/maps/index`
												});
												// #endif
												// #ifdef H5
												this.$Router.push(`/pages/maps/orderTracking?num=${arr[1]}&url=/pages/maps/index`);
												// #endif
											});
										}, 1000);
									}
								}
							}

							break;

						case 'ios':
							const content2 = JSON.parse(msg.payload);
							if (content2.billCode) {
								setTimeout(() => {
									this.$nextTick(function() {
										// #ifdef APP-PLUS
										uni.redirectTo({
											url: `/pages/maps/orderTracking?num=${content2.billCode}&url=/pages/maps/index`
										});
										// #endif
										// #ifdef H5
										this.$Router.push(`/pages/maps/orderTracking?num=${content2.billCode}&url=/pages/maps/index`);
										// #endif
									});
								}, 1000);
							} else if (content2.title == 'RMB Exchange Rate update') {
								setTimeout(() => {
									this.$nextTick(function() {
										// #ifdef APP-PLUS
										uni.redirectTo({
											url: `/pages/exchangeRate/index`
										});
										// #endif
										// #ifdef H5
										this.$Router.push(`/pages/exchangeRate/index`);
										// #endif
									});
								}, 1000);
							}
							break;
					}
				}
			}
		},
		// 获取消息通知权限
		judgeIosPermissionPush() {
			const isIos = plus.os.name == 'iOS';
			if (isIos) {
				// ios
				var isOn = undefined;
				var types = 0;
				var app = plus.ios.invoke('UIApplication', 'sharedApplication');
				var settings = plus.ios.invoke(app, 'currentUserNotificationSettings');
				if (settings) {
					types = settings.plusGetAttribute('types');
					plus.ios.deleteObject(settings);
				} else {
					types = plus.ios.invoke(app, 'enabledRemoteNotificationTypes');
				}
				plus.ios.deleteObject(app);
				//isOn 保存苹果通知栏打开的状态返回值为true或false
				isOn = 0 != types;
				if (!isOn) {
					uni.showModal({
						title: 'Notification permission enable reminder',
						content: "You don't have the permission to open the notification. You can't receive the message notification. Please go to settings!",
						showCancel: false,
						confirmText: 'Go to Settings',
						success: function(res) {
							if (res.confirm) {
								var app = plus.ios.invoke('UIApplication', 'sharedApplication');
								var setting = plus.ios.invoke('NSURL', 'URLWithString:', 'app-settings:');
								plus.ios.invoke(app, 'openURL:', setting);
								plus.ios.deleteObject(setting);
								plus.ios.deleteObject(app);
							}
						}
					});
				}
			} else {
				// android
				var main = plus.android.runtimeMainActivity();
				var pkName = main.getPackageName();
				var uid = main.getApplicationInfo().plusGetAttribute('uid');
				var NotificationManagerCompat = plus.android.importClass('android.support.v4.app.NotificationManagerCompat');
				//android.support.v4升级为androidx
				if (NotificationManagerCompat == null) {
					NotificationManagerCompat = plus.android.importClass('androidx.core.app.NotificationManagerCompat');
				}
				//areNotificationsEnabled 保存安卓通知栏打开的状态返回值为true或false
				var areNotificationsEnabled = NotificationManagerCompat.from(main).areNotificationsEnabled();
				if (!areNotificationsEnabled) {
					uni.showModal({
						title: 'Notification permission enable reminder',
						content: "You don't have the permission to open the notification. You can't receive the message notification. Please go to settings!",
						showCancel: false,
						confirmText: 'Go to Settings',
						success: function(res) {
							if (res.confirm) {
								var Intent = plus.android.importClass('android.content.Intent');
								var Build = plus.android.importClass('android.os.Build');
								//android 8.0引导
								if (Build.VERSION.SDK_INT >= 26) {
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('android.provider.extra.APP_PACKAGE', pkName);
								} else if (Build.VERSION.SDK_INT >= 21) {
									//android 5.0-7.0
									var intent = new Intent('android.settings.APP_NOTIFICATION_SETTINGS');
									intent.putExtra('app_package', pkName);
									intent.putExtra('app_uid', uid);
								} else {
									//(<21)其他--跳转到该应用管理的详情页
									intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
									var uri = Uri.fromParts('package', mainActivity.getPackageName(), null);
									intent.setData(uri);
								}
								// 跳转到该应用的系统通知设置页
								main.startActivity(intent);
							}
						}
					});
				}
			}
		},
		// 获取当前页面路由
		getOnePages() {
			this.$nextTick(function() {
				let currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let currentRoute = currentRoutes[currentRoutes.length - 1].route; //获取当前页面路由
				let currentParam = currentRoutes[currentRoutes.length - 1].options; //获取路由参数
				// 拼接参数
				let param = '';
				for (let key in currentParam) {
					param += '?' + key + '=' + currentParam[key];
				}
				let localRoute = currentRoute + param;
				let saomaType = getStorage('saomaType');
				if (localRoute == 'pages/home/index' && saomaType == 'off') {
					const isAndroid = uni.getSystemInfoSync().platform;
					switch (isAndroid) {
						case 'android':
							preventSystemBackModal.setUp({
								enable: false //是否拦截系统返回功能
							});
							setStorage('saomaType', 'on');
							break;
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
/* #ifndef APP-PLUS-NVUE */
uni-page-body,
.uni-body,
#app,
page {
	height: 100%;
}

/* #endif */
/* 解决头条小程序组件内引入字体不生效的问题 */

/* #ifdef MP-TOUTIAO */
@font-face {
	font-family: uniicons;
	src: url('/static/uni.ttf');
}

/* #endif */

/* #ifdef APP-PLUS-NVUE */
// @font-face {
// 	font-family: 'DIN';
// 	src: url('/common/DIN/DBHelvethaicaXv3.2.ttf');
// 	font-weight: normal;
// 	font-style: normal;
// 	font-display: swap;
// }
.uni-body,
body {
	font-family: 'DIN' !important;
}
/* #endif */
// .DIN {
// 	font-family: 'DIN' !important;
// }
</style>
